package com.druid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.druid.entity.CeSecurityPermission;
import com.druid.entity.CeSecurityRole;
import com.druid.entity.CeSecurityRolePermission;
import com.druid.mapper.managementmapper.CeSecurityRolePermissionMapper;
import com.druid.model.PageBody;
import com.druid.request.PageParam;
import com.druid.request.RolePermissionParam;
import com.druid.response.SecurityRolePermissionVm;
import com.druid.service.managementservice.ICeSecurityPermissionService;
import com.druid.service.managementservice.ICeSecurityRolePermissionService;
import com.druid.service.managementservice.ICeSecurityRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台管理角色权限表 服务实现类
 * </p>
 *
 * @author druid-elf
 * @since 2019-12-25
 */
@Service
@RequiredArgsConstructor
public class CeSecurityRolePermissionServiceImpl extends ServiceImpl<CeSecurityRolePermissionMapper, CeSecurityRolePermission> implements ICeSecurityRolePermissionService {

    private final ICeSecurityRoleService iCeSecurityRoleService;

    private final ICeSecurityPermissionService iCeSecurityPermissionService;

    /**
     * 得到角色权限前端展示视图
     *
     * @param pageParam 分页参数对象
     * @return 分页参数列表
     */
    @Override
    public PageBody<SecurityRolePermissionVm> getRolePermissionVmList(PageParam pageParam) {

        //  获取角色列表
        IPage<CeSecurityRole> page = iCeSecurityRoleService.page(new Page<>(pageParam.getPageNum(), pageParam.getPageSize()));

        //  获取角色权限前端返回视图
        List<SecurityRolePermissionVm> collect = page.getRecords().stream().map(o -> {

            //  获取角色对应的权限
            String sqlWhere = "id IN ( SELECT permission_id FROM ce_security_role_permission WHERE role_id = {0} )";
            List<CeSecurityPermission> list = iCeSecurityPermissionService.list(new LambdaQueryWrapper<CeSecurityPermission>().apply(sqlWhere, o.getRoleId()));

            return SecurityRolePermissionVm
                    .builder()
                    .roleName(o.getName())
                    .roleId(o.getRoleId())
                    .ceSecurityPermissions(list)
                    .build();
        }).collect(Collectors.toList());

        return PageBody.dealWithList( page, collect );
    }

    /**
     * 批量修改角色权限表
     *
     * @param pageParamLists 角色权限视图集
     * @return true 成功 false 失败
     */
    @Override
    public boolean updateBatchRolePermissionList(List<List<RolePermissionParam>> pageParamLists) {

        //  将二维集合扁平化合并成一维数组
        List<RolePermissionParam> rolePermissionParamList = pageParamLists.stream().flatMap(Collection::stream).collect(Collectors.toList());

        //  获取有权限的角色权限数据
        List<CeSecurityRolePermission> hasPerrolePermissionParamList = rolePermissionParamList.stream().filter(RolePermissionParam::isHasPermission).map(
                    rolePermissionParam -> CeSecurityRolePermission.builder().roleId(rolePermissionParam.getRoleId()).permissionId(rolePermissionParam.getPermissionId()).build()
            )
                    .collect(Collectors.toList());


        //  获取没有权限的角色的数据
        List<CeSecurityRolePermission> hasNotPerrolePermissionParamList = rolePermissionParamList.stream().filter(rolePermissionParam -> !rolePermissionParam.isHasPermission()).map(
                    rolePermissionParam -> CeSecurityRolePermission.builder().roleId(rolePermissionParam.getRoleId()).permissionId(rolePermissionParam.getPermissionId()).build()
            )
                    .collect(Collectors.toList());


        //  拼接删除无权限的条件
        LambdaQueryWrapper<CeSecurityRolePermission> deleteWrapper = jointString(hasNotPerrolePermissionParamList);

        //  拼接有权限的查询条件
        LambdaQueryWrapper<CeSecurityRolePermission> selectWrapper = jointString(hasPerrolePermissionParamList);

        //  通过查询表里存在的数据将权限角色的权限数据过滤掉
        List<CeSecurityRolePermission> existList = list(selectWrapper);
        if ( !CollectionUtils.isEmpty(existList) ) existList = existList
                .stream()
                .map(
                        ceSecurityRolePermission -> CeSecurityRolePermission.builder().roleId(ceSecurityRolePermission.getRoleId()).permissionId(ceSecurityRolePermission.getPermissionId()).build()
                ).collect(Collectors.toList());

        //  清除库里面已经存在的权限
       hasPerrolePermissionParamList.removeAll( existList );

        //   批量删除角色权限
        boolean jduge = remove(deleteWrapper);

        //  批量修改或者增加角色权限
        if ( !CollectionUtils.isEmpty(hasPerrolePermissionParamList) && saveOrUpdateBatch(hasPerrolePermissionParamList) ) jduge = true;

        return jduge;
    }

    /**
     * 根据集合数据拼接对应的业务sql
     * @param permissionParamList  集合条件数据
     * @return  查询条件器
     */
    private LambdaQueryWrapper<CeSecurityRolePermission>  jointString ( List<CeSecurityRolePermission> permissionParamList ) {

        //  拼接有权限的查询条件
        LambdaQueryWrapper<CeSecurityRolePermission> wrapper = new LambdaQueryWrapper<>();

        if ( !CollectionUtils.isEmpty(permissionParamList) ) {

            for (CeSecurityRolePermission ceSecurityRolePermission : permissionParamList) {

                wrapper.apply( "( role_id = {0} and permission_id = {1} )",ceSecurityRolePermission.getRoleId(),ceSecurityRolePermission.getPermissionId()).or();
            }
        }
        wrapper.apply("1=2");

        return wrapper;
    }

}
